<template>
  <div class="page-management">
    <div class="header">
      <h2>页面管理</h2>
      <el-button type="primary" @click="openPageForm">
        <el-icon><Plus /></el-icon>
        新建页面
      </el-button>
    </div>

    <!-- 页面列表 -->
    <el-table 
      :data="pages" 
      style="width: 100%" 
      v-loading="loading.pages"
      empty-text="暂无页面数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" width="120" show-overflow-tooltip />
      <el-table-column prop="code" label="代码" width="100" show-overflow-tooltip />
      <el-table-column prop="description" label="描述" width="150" show-overflow-tooltip />
      <el-table-column prop="display_order" label="排序" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editPage(scope.row)">
            编辑
          </el-button>
          <el-button size="small" @click="viewContent(scope.row)">
            查看
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="deletePage(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页面表单对话框 -->
    <PageForm
      v-model:visible="pageFormVisible"
      :form-data="currentPage"
      :is-edit="isEditPage"
      :all-categories="categories"
      @save="handleSavePage"
      @cancel="closePageForm"
      @add-category-relation="addCategoryToPage"
      @remove-category-relation="removeCategoryFromPage"
    />

    <!-- 内容查看对话框 -->
    <ContentViewer
      v-model:visible="contentViewerVisible"
      :content="viewerContent"
      :title="viewerTitle"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import PageForm from './PageForm.vue'
import ContentViewer from './ContentViewer.vue'

// Props
const props = defineProps({
  pages: {
    type: Array,
    default: () => []
  },
  categories: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Object,
    default: () => ({ pages: false })
  }
})



// Events
const emit = defineEmits([
  'save-page',
  'delete-page',
  'refresh-data',
  'add-category-relation',
  'remove-category-relation'
])

// 响应式数据
const pageFormVisible = ref(false)
const contentViewerVisible = ref(false)
const currentPage = ref({})
const isEditPage = ref(false)
const viewerContent = ref('')
const viewerTitle = ref('')

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}



// 打开页面表单
const openPageForm = () => {
  currentPage.value = {
    title: '',
    slug: '',
    content: '',
    status: 'draft'
  }
  isEditPage.value = false
  pageFormVisible.value = true
}

// 编辑页面
const editPage = (page) => {
  console.log('🚨🚨🚨🚨🚨 PageManagement.vue - editPage 函数被调用！！！ 🚨🚨🚨🚨🚨')
  console.log('🚨🚨🚨🚨🚨 这是 PageManagement 内部的 editPage 函数！！！ 🚨🚨🚨🚨🚨')
  console.log('🔍 PageManagement - page:', page)
  console.log('🔍 PageManagement - 当前时间:', new Date().toLocaleTimeString())
  
  currentPage.value = { ...page }
  isEditPage.value = true
  pageFormVisible.value = true
  
  console.log('✅ PageManagement - editPage 执行完成，pageFormVisible:', pageFormVisible.value)
  console.log('🚨🚨🚨🚨🚨 PageManagement.vue - editPage 函数执行完毕！！！ 🚨🚨🚨🚨🚨')
}

// 关闭页面表单
const closePageForm = () => {
  pageFormVisible.value = false
  currentPage.value = {}
  isEditPage.value = false
}

// 保存页面
const handleSavePage = (pageData, isEdit) => {
  console.log('🚨🚨🚨 PageManagement - handleSavePage 被调用 🚨🚨🚨')
  console.log('🔍 PageManagement - 函数参数数量:', arguments.length)
  console.log('🔍 PageManagement - pageData:', pageData)
  console.log('🔍 PageManagement - isEdit 参数:', isEdit)
  console.log('🔍 PageManagement - isEditPage.value:', isEditPage.value)
  console.log('🔍 PageManagement - pageFormVisible.value:', pageFormVisible.value)
  console.log('🔍 PageManagement - emit 函数:', emit)
  console.log('🔍 PageManagement - 即将触发 save-page 事件')
  
  // 使用传入的 isEdit 参数，如果没有则使用本地状态
  const editMode = isEdit !== undefined ? isEdit : isEditPage.value
  
  console.log('🔍 PageManagement - 最终使用的 editMode:', editMode)
  console.log('🔍 PageManagement - 即将调用 emit(save-page)')
  
  try {
    emit('save-page', pageData, editMode)
    console.log('✅ PageManagement - save-page 事件已触发成功')
  } catch (emitError) {
    console.error('❌ PageManagement - emit 调用失败:', emitError)
  }
  
  console.log('✅ PageManagement - save-page 事件已触发，即将关闭表单')
  closePageForm()
  console.log('✅ PageManagement - 表单已关闭，handleSavePage 执行完成')
}

// 删除页面
const deletePage = async (page) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除页面 "${page.title}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    emit('delete-page', page.id)
  } catch {
    // 用户取消删除
  }
}

// 查看内容
const viewContent = (page) => {
  viewerTitle.value = page.title
  viewerContent.value = page.content || '暂无内容'
  contentViewerVisible.value = true
}

// 添加分类关系
const addCategoryToPage = (relationData) => {
  console.log('🔍 PageManagement - addCategoryToPage 被调用:', relationData)
  emit('add-category-relation', relationData)
}

// 移除分类关系
const removeCategoryFromPage = (relationData) => {
  console.log('🔍 PageManagement - removeCategoryFromPage 被调用:', relationData)
  emit('remove-category-relation', relationData)
}
</script>

<style scoped>
.page-management {
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: 100vh;
  width: calc(100vw - 250px);
  margin: 0;
  position: fixed;
  top: 0;
  left: 250px;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  transition: all 0.3s ease;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px 24px;
  margin: -20px -20px 24px -20px;
  font-size: 18px;
  font-weight: 700;
  color: white;
  border-bottom: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  border-radius: 12px 12px 0 0;
  flex-shrink: 0;
}

.header h2 {
  margin: 0;
  color: white;
  font-size: 28px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 表格容器 */
.el-table {
  flex: 1;
  min-height: 0;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 全局按钮样式美化 */
:deep(.el-button) {
  padding: 10px 18px !important;
  font-size: 14px !important;
  font-weight: 600 !important;
  border-radius: 10px !important;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.12) !important;
  transition: all 0.3s ease !important;
  border: none !important;
  min-height: 38px !important;
  min-width: 80px !important;
}

:deep(.el-button--default) {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
  color: #333 !important;
}

:deep(.el-button:hover) {
  transform: translateY(-2px) !important;
  box-shadow: 0 5px 16px rgba(0, 0, 0, 0.18) !important;
}

:deep(.el-button--default:hover) {
  background: linear-gradient(135deg, #e3e7f0 0%, #b1c1d8 100%) !important;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
  box-shadow: 0 5px 16px rgba(102, 126, 234, 0.4) !important;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
  color: white !important;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #0e8078 0%, #2dd865 100%) !important;
  box-shadow: 0 5px 16px rgba(17, 153, 142, 0.4) !important;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
}

:deep(.el-button--warning:hover) {
  background: linear-gradient(135deg, #ee82f9 0%, #f3455a 100%) !important;
  box-shadow: 0 5px 16px rgba(240, 147, 251, 0.4) !important;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  color: white !important;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #ff5252 0%, #e53e3e 100%) !important;
  box-shadow: 0 5px 16px rgba(255, 107, 107, 0.4) !important;
}

/* 表格操作按钮样式 */
:deep(.el-button--small) {
  padding: 8px 16px !important;
  font-size: 13px !important;
  min-height: 34px !important;
  min-width: 70px !important;
}

:deep(.el-table .el-button) {
  padding: 8px 16px !important;
  font-size: 14px !important;
  min-height: 36px !important;
  min-width: 80px !important;
}

/* 操作列不换行 */
:deep(.el-table__body .el-table__row .el-table__cell:last-child) {
  white-space: nowrap !important;
}

:deep(.el-table__body .el-table__row .el-table__cell:last-child .cell) {
  white-space: nowrap !important;
  overflow: visible !important;
}

/* 图标样式 */
:deep(.el-icon) {
  margin-right: 8px !important;
  font-size: 18px !important;
}

/* 表格头部样式 */
:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  font-weight: 600;
  color: #303133;
}

/* 表格行样式 */
:deep(.el-table tbody tr:hover) {
  background: rgba(64, 158, 255, 0.05);
}

/* 标签样式 */
:deep(.el-tag) {
  padding: 4px 10px !important;
  font-size: 12px !important;
  font-weight: 600 !important;
  border-radius: 6px !important;
  border: none !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important;
  color: white !important;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%) !important;
  color: white !important;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%) !important;
  color: white !important;
}

/* 滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}
</style>